package com.buaa.airticketbookingsystem.Controller;

import com.buaa.airticketbookingsystem.Entity.Flight;
import com.buaa.airticketbookingsystem.Entity.Ticket;
import com.buaa.airticketbookingsystem.Service.FlightService;
import com.buaa.airticketbookingsystem.Service.TicketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
@CrossOrigin
@RestController
public class AddNewFlightController {

    @Autowired
    private FlightService flightService;

    @Autowired
    private TicketService ticketService;

    @PostMapping("/admin/addNewFlight")
    public Map<String, Object> addNewFlight(@RequestBody Map<String, String> remap){
        Map<String, Object> map = new HashMap<>();
        String f_id = remap.get("f_id");
        String start_airport = remap.get("start_airport");
        String end_airport = remap.get("end_airport");
        String start_time = remap.get("start_time").substring(8);
        String end_time = remap.get("end_time").substring(8);
        String lines_number = remap.get("lines_number");
        String price = remap.get("price");
        String date = remap.get("start_time").substring(0,8);
        String airline = remap.get("airline");
        try {
            if (flightService.selectFlightByID(f_id) == null) {
                int ln = Integer.parseInt(lines_number);
                double p = Double.parseDouble(price);
                flightService.addNewFlight(new Flight(f_id, start_airport, end_airport, start_time, end_time, ln, airline, date, p, start_airport.substring(0, 2), end_airport.substring(0, 2)));
                for (int j = 1; j <= ln ; j++) {
                    for (char k = 'A'; k <= 'F'; k++) {
                        ticketService.addNewTicket(new Ticket(f_id + j + String.valueOf(k), f_id, Integer.toString(j) + String.valueOf(k), p, date, start_time, end_time));
                    }
                }
                map.put("res", true);
                map.put("message", "添加航班成功！");
            }
            else {
                map.put("res", true);
                map.put("message", "该航班已经存在！");
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            map.put("res", false);
            map.put("message", "添加航班失败！");
        }
        return map;
    }

}